package com.crishne.anwo.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.crishne.anwo.config.ConfigInfo;
import com.crishne.anwo.constant.JsonStringConstant;
import com.crishne.anwo.model.Role;
import com.crishne.anwo.model.User;
import com.crishne.anwo.model.UserMap;
import com.crishne.anwo.service.RoleService;
import com.crishne.anwo.service.UserMapService;
import com.crishne.anwo.service.UserService;
import com.crishne.anwo.utill.AclSecurityUtil;
import com.crishne.anwo.utill.CommonImageView;
import com.crishne.anwo.utill.CommonUtill;
import com.crishne.anwo.utill.FileDownloadView;
import com.crishne.anwo.utill.MatrixToImageWriter;
import com.crishne.anwo.utill.PaginationUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;

@Controller
@RequestMapping("sysmgr/user/")
public class UserController {
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private RoleService roleService;
	
	@Autowired
	private UserMapService userMapService;
	
	@Autowired
	private ConfigInfo configInfo;

	
	private CommonUtill commonUtill = new CommonUtill();
	
	private AclSecurityUtil _asu = AclSecurityUtil.getInstance(AclSecurityUtil.ALGORITHM_SHA1);


	//返回jsp视图
	@RequestMapping(value = "user_main")
	public String user_main(){
		return "admin/sysmgr/user_main";
	}

	@RequestMapping("saveOrEditUser")
	public void saveOrEditUser(HttpServletResponse response,HttpServletRequest request) throws Exception{
		//获取参数
    	String userId = request.getParameter("userId");
		String userName = request.getParameter("userName");
		String stName = request.getParameter("stName");
		String userPwd = request.getParameter("userPwd");
		String nmOrder = request.getParameter("nmOrder");
		String stTelPhone = request.getParameter("stTelPhone");
		
		//不允许重名
		User checkUser = userService.getUserByName(userName);
		if(null == userId || "".equals(userId)){
			if(null != checkUser){
				JSONObject jsonString = JsonStringConstant.getNoDataSuccessMessage("该用户名已经存在，保存失败！");

				commonUtill.OutputJson(jsonString, response, request);
		        return;
			}
		}
		else{
			if(null != checkUser && !checkUser.getStUserId().equals(userId)){
				JSONObject jsonString = JsonStringConstant.getNoDataSuccessMessage("该用户名已经存在，保存失败！");

				commonUtill.OutputJson(jsonString, response, request);
		        return;
			}
		}
		
		
		User tUser = null;
		if(null == userId || "".equals(userId)){
			tUser = new User();
		}
		else{
			tUser = userService.getUserById(userId);
		}
		tUser.setStUserName(userName);
		tUser.setStName(stName);
		if(null != nmOrder && !"".equals(nmOrder)){
			tUser.setNmOrder(Integer.valueOf(nmOrder));
		}
		else{
			tUser.setNmOrder(0);
		}
		tUser.setStTelPhone(stTelPhone);
		
		
		if(null != userPwd && !"".equals(userPwd)){
			AclSecurityUtil asu = AclSecurityUtil.getInstance(AclSecurityUtil.ALGORITHM_SHA1);
			tUser.setStUserPwd(asu.encodePassword(userPwd));
		}
		
		if(null == userId || "".equals(userId)){
			tUser.setStUserId(UUID.randomUUID().toString());
			tUser.setStStatus("1");//0 表示超级管理员，所以添加的都需要设置为1
			tUser.setDtCreate(new Date());
			userService.addUser(tUser);
		}
		else{
			userService.updateUser(tUser);
		}
		
		JSONObject jsonString = JsonStringConstant.getNoDataSuccessMessage("保存成功！");

		commonUtill.OutputJson(jsonString, response, request);
    }
	
	@RequestMapping("findUsers")
	public void findUsers(HttpServletResponse response,HttpServletRequest request){
		List<User> userList = userService.findUsers("1");
		JSONObject jsonString = JsonStringConstant.getSuccessMessage(userList);

		commonUtill.OutputJson(jsonString, response, request);
    }
	
	@SuppressWarnings("unchecked")
	@RequestMapping("getUserPageList")
	public void getUserPageList(HttpServletResponse response,HttpServletRequest request){
		//获取当前页 和 一页显示的数据数目
		String conCurrentPage = request.getParameter("currentpage");
		String stPageSize = request.getParameter("pageSize");
		Integer currentpage = 1;
		Integer pageSize = 10;
		if(conCurrentPage != null && !"".equals(conCurrentPage)){
			currentpage = Integer.valueOf(conCurrentPage);
		}
		
		if(stPageSize != null && !"".equals(stPageSize)){
			pageSize = Integer.valueOf(stPageSize);
		}
		
		//开始获取查询条件
		String  condUserName = request.getParameter("username");
		@SuppressWarnings("rawtypes")
		HashMap searchCondition = new HashMap();
		searchCondition.put("condDefault","1=1");
		if(null !=condUserName && !"".equals(condUserName) ){
			searchCondition.put("condUserName","st_name like '%"+condUserName+"%'");
		}
		
		//构造 PaginationUtil
		PaginationUtil<User> pageUtil = new PaginationUtil<User>();
		pageUtil.setCurrentPage(currentpage);
		pageUtil.setPageSize(pageSize);
		pageUtil.setStOrderBy("nm_order desc");
		pageUtil.setSearchCondition(searchCondition);
		PaginationUtil<User> userList = userService.searchUsers(pageUtil);
		JSONObject jsonString = JsonStringConstant.getSuccessMessage(userList);

		commonUtill.OutputJson(jsonString, response, request);
    }
	
	@RequestMapping("getRecords")
	public void getRecords(HttpServletResponse response,HttpServletRequest request){
		String sql = "select * from t_user";
		Object ojson =  JsonStringConstant.getSuccessMessage(userService.findRecords(sql));
		commonUtill.OutputJson(ojson, response, request);
	}
	
	@RequestMapping("getUserEdit")
	public void getUserEdit(HttpServletResponse response,HttpServletRequest request)
	{
		String userid = request.getParameter("userid");
		User tUser = userService.getUserById(userid);
		
		HashMap retData = new HashMap();
		retData.put("userinfo", tUser);
		//retData.put("allroles", roleService.getAllRoles());
		JSONObject jsonString = JsonStringConstant.getSuccessMessage(retData);
		commonUtill.OutputJson(jsonString,response,request);
	}
	
	@RequestMapping("deleteUser")
    public void deleteUser(HttpServletResponse response,HttpServletRequest request){
    	String userIds = request.getParameter("userId");
    	JSONObject jsonString = new JSONObject();
    	try{
    		userService.deleteUser(userIds);
    		jsonString = JsonStringConstant.getNoDataSuccessMessage("删除成功！");
    	}
    	catch(Exception ex){
    		jsonString = JsonStringConstant.getNoDataSuccessMessage("删除失败！");
    	}
		commonUtill.OutputJson(jsonString, response, request);
    }
    
    @RequestMapping("getUserMapRole")
    public void getUserMapRole(HttpServletResponse response,HttpServletRequest request){
    	String userId = request.getParameter("userid");
    	//User tUser = userService.getUserById(userId);
    	List<UserMap> userMapList = userMapService.getUserMapRoles(userId);
    	List<Role> roleList = roleService.getAllRoles();
    	HashMap retMap = new HashMap();
    	retMap.put("userMap", userMapList);
    	retMap.put("roleList", roleList);
    	JSONObject jsonString = JsonStringConstant.getSuccessMessage(retMap);
		commonUtill.OutputJson(jsonString, response, request);
    }
    
    @RequestMapping("saveUserMapRoles")
	public void saveUserMapRoles(HttpServletResponse response,HttpServletRequest request) throws Exception{
		//获取参数
    	String userId = request.getParameter("userId");
		String userMapRoles = request.getParameter("rolemaps");
		String[] roleIds = userMapRoles.split(",");
		userMapService.saveRoleMaps(userId,roleIds);
		
		
		JSONObject jsonString = JsonStringConstant.getNoDataSuccessMessage("保存成功！");

		commonUtill.OutputJson(jsonString, response, request);
    }
	
	@RequestMapping("addFileSubmit")
    public void addFileSubmit(HttpServletResponse response,HttpServletRequest request){
    	//ModelAndView mv=new ModelAndView("upAndDownLoad"); 
    	String path = request.getSession().getServletContext().getRealPath(configInfo.getUploadDir()); 
    	
    	//String userid = request.getParameter("userid");
    	
    	MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;     
    	// 获得文件：     
    	MultipartFile file = multipartRequest.getFile("stFile");

    	String fileName = file.getOriginalFilename(); 
    	File targetFile = new File(path, fileName);  
    	if(!targetFile.exists()){
    		targetFile.mkdirs();  
    	}  
    	//保存  
    	try {
    		file.transferTo(targetFile);
    	} catch (Exception e) {
    		e.printStackTrace();  
    	}
    	
    	try {
			response.getWriter().println("<script>parent.document.getElementById('alerthandler').click();</script>");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

    	//mv.addObject("allmenus",allmenus);
    	//mv.addObject("fileName",fileName);
    	//return mv;//转发，带参数
    }
	
	@RequestMapping("ajaxAddFileSubmit")
    public void ajaxAddFileSubmit(@RequestParam(value = "file", required = false)MultipartFile file,HttpServletResponse response,MultipartHttpServletRequest request){
    	//ModelAndView mv=new ModelAndView("upAndDownLoad"); 
    	String path = request.getSession().getServletContext().getRealPath(configInfo.getUploadDir()); 
    	
    	//String userid = request.getParameter("userid");
    	
    	MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;     
    	// 获得文件：     
    	//MultipartFile file = multipartRequest.getFile("stFile");

    	String fileName = file.getOriginalFilename(); 
    	File targetFile = new File(path, fileName);  
    	if(!targetFile.exists()){
    		targetFile.mkdirs();  
    	}  
    	//保存  
    	try {
    		file.transferTo(targetFile);
    	} catch (Exception e) {
    		e.printStackTrace();  
    	}
    	
    	try {
			response.getWriter().println("<script>parent.document.getElementById('alerthandler').click();</script>");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

    	//mv.addObject("allmenus",allmenus);
    	//mv.addObject("fileName",fileName);
    	//return mv;//转发，带参数
    }

	
	@RequestMapping("downLoadSubmit")
    public ModelAndView downloadSubmit(HttpServletResponse response,HttpServletRequest request){
		HashMap map = new HashMap();
		String path = request.getSession().getServletContext().getRealPath(configInfo.getUploadDir()+File.separatorChar+"10.png"); 
		
		File file = new File(path);
    	try {
    		byte[] byContent = FileUtils.readFileToByteArray(file);
    		map.put("byContent", byContent);
		} catch (IOException e) {
			e.printStackTrace();
		}
    	
    	map.put("stFilename", "b.png");
    	ModelAndView mv=new ModelAndView(new FileDownloadView(),map); 
        return mv;//转发，带参数
    }
	
	
	@RequestMapping("qcodeGenSubmit")
    public ModelAndView qcodeGenSubmit(HttpServletResponse response,HttpServletRequest request){
		//ModelAndView mv=new ModelAndView("zxing/qrcode"); 
    	String content = request.getParameter("qcodeName");
    	//直接生成图片文件
//    	try {
//    		//String path = request.getContextPath();
//    		//String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
//    	     String realpath = "D:/zxing/";
//    	     
//    	     MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
//    	     
//    	     Map hints = new HashMap();
//    	     hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
//    	     BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 400, 400,hints);
//    	     File file1 = new File(realpath,"qrcode.png");
//    	     MatrixToImageWriter.writeToFile(bitMatrix, "png", file1);
//    	     
//    	 } catch (Exception e) {
//    	     e.printStackTrace();
//    	 }
    	
    	//生成图片试图
    	HashMap viewmap = new HashMap();
    	try {
    		//String path = request.getContextPath();
    		//String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    	     //String realpath = "D:/zxing/";
    		
    		viewmap.put("stFilename", "qcode.png");
    		//byte[] byContent = new byte[1024];
        	
    	     
    	     MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
    	     
    	     Map hints = new HashMap();
    	     hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
    	     BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 400, 400,hints);
    	     //File file1 = new File(realpath,"qrcode.jpg");
    	     //MatrixToImageWriter.writeToFile(bitMatrix, "jpg", file1);
    	     BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
    	     //byte[] data = ((DataBufferByte) image.getData().getDataBuffer()).getData();
    	     ByteArrayOutputStream baos = new ByteArrayOutputStream();
    	     ImageIO.write(image,"jpg",baos);
    	     viewmap.put("byContent", baos.toByteArray());
    	     
    	 } catch (Exception e) {
    	     e.printStackTrace();
    	 }
    	ModelAndView mv=new ModelAndView(new CommonImageView(),viewmap); 
        return mv;//转发，带参数
    }
	
}